/*
 * @Copyright: 2025 Copyright (C) AMCAX, All rights reserved.
 * @Author: Zhang
 * @Date: 2025/7/24 19:39
 * @LastEditTime: 2025/7/24 19:39
 * @LastEditors: Zhang
 * @Description:
 */
import { modelLayout } from '@/domain';
import { CmdDialogForm } from 'nextcae-base';
import { useEffect, useRef, useState } from 'react';
import { NMMeshBaseCommand, TopoDialogProps } from '../type';
import CmdInteractor from './CmdInteractor';
import { schema, uiSchema } from './data';
import { widgetManager } from '@/common/managers';
import './index.scss';
import { useDocumentStore } from '@/common/store';

const TrajectoriesDialog = ({ title, onClose }: TopoDialogProps) => {
  const [formData, setFormData] = useState(); // 表单数据
  const [isFormDataValid, setIsFormDataValid] = useState(false); // 确定按钮是否可操作
  const cmdRef = useRef<CmdInteractor>(null); // 拾取组件
  const { workingObject } = useDocumentStore();

  useEffect(() => {
    cmdRef.current = new CmdInteractor(setIsFormDataValid);
    return () => {
      cmdRef.current.destroy();
      cmdRef.current = null;
    };
  }, []);

  useEffect(() => {
    widgetManager.hint('进入模型布线轨迹线命令!');
    return () => {
      widgetManager.hint();
    };
  }, []);

  // 提交
  const onSubmit = async () => {
    const getDataInfo = cmdRef.current.getDataInfo();
    const params = {
      type: 'track',
      root: workingObject,
      fidx: getDataInfo.fidx,
      points: getDataInfo.point.flat(),
    };
    await modelLayout.createCurve(params);
    onClose();
  };

  return (
    <>
      <CmdDialogForm
        title={title}
        titleIcon={'commands/modelRouting/track'}
        schema={schema}
        extraUiSchema={uiSchema}
        formData={formData}
        fields={{}}
        onChange={(data) => {
          setFormData(data.formData);
        }}
        onSubmit={onSubmit}
        onClose={onClose}
        isFormDataValid={isFormDataValid}
        width='300px'
        formClassName='structure-form'
      />
    </>
  );
};
export const cmdTrajectories: NMMeshBaseCommand = {
  id: 'cmdTrajectories',
  icon: 'commands/modelRouting/track',
  label: '轨迹线',
  create: (label: string, onClose: () => void, props) => (
    <TrajectoriesDialog
      title={label}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
